package com.example.shop_2302.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.LoginEntity
import com.example.base.entity.Res
import com.example.base.entity.SendCodeEntity
import com.example.base.mvvm.BaseViewModel
import com.example.shop_2302.utils.SingleLiveData
import kotlinx.coroutines.launch

class LoginViewModel:BaseViewModel() {
    //返回值--发送验证
    val sendSuccess = SingleLiveData<Res<SendCodeEntity>>()
    val sendFail = MutableLiveData<String>()
    fun sendCode(phone:String){
        //在作用域中调用挂起函数   自己添加try-catch ,防止有异常情况时，项目直接崩溃
        viewModelScope.launch {
            try {
                sendSuccess.postValue(apiServer.sendCode(phone))
            }catch (e:Exception){
                sendFail.postValue(e.message)
            }

        }
    }
    //返回值--验证码登录
    val codeSuccess = SingleLiveData<Res<LoginEntity>>()
    val codeFail = SingleLiveData<String>()
    fun loginCode(captcha:String,phone:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["captcha"] = captcha
                map["phone"] = phone
                codeSuccess.postValue(apiServer.loginCode(mapToBody(map)))
            }catch (e:Exception){
                codeFail.postValue(e.message.toString())
            }
        }
    }

}